package com.sky.service.user.impl;

import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.mapper.user.DishMapper;
import com.sky.mapper.user.SetmealMapper;
import com.sky.mapper.user.ShoppingCartMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.Setmeal;
import com.sky.pojo.ShoppingCart;
import com.sky.service.user.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Override
    public void add(ShoppingCartDTO dto) {
        if (null==dto||null==dto.getDishId()&&null==dto.getSetmealId()){
            throw new NullPointerException(MessageConstant.ILLEGAL);
        }
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(dto,shoppingCart);
        //设置公共字段
        shoppingCart.setUserId(BaseContext.getCurrentId());
        shoppingCart.setCreateTime(LocalDateTime.now());
        shoppingCart.setNumber(1);
        if (null==shoppingCart.getDishId()){//说明是套餐
         Setmeal setmeal = setmealMapper.selectById(shoppingCart.getSetmealId());
            shoppingCart.setName(setmeal.getName());
            shoppingCart.setImage(setmeal.getImage());
            shoppingCart.setAmount(setmeal.getPrice());
        }else {//到这儿说明是菜品
         Dish dish =   dishMapper.selectById(shoppingCart.getDishId());
         shoppingCart.setName(dish.getName());
         shoppingCart.setAmount(dish.getPrice());
         shoppingCart.setImage(dish.getImage());
        }
       List<ShoppingCart> carts= shoppingCartMapper.selectByUserId(shoppingCart.getUserId());
        if (null==carts){
            shoppingCartMapper.save(shoppingCart);
        }
        for (ShoppingCart cart : carts) {
            if (null!=cart.getDishId()&& cart.getDishId().equals(shoppingCart.getDishId())||
                 null!=cart.getSetmealId()&& cart.getSetmealId().equals(shoppingCart.getSetmealId())){
                cart.setNumber(cart.getNumber()+1);
                shoppingCartMapper.updete(cart);
                return;
          }
        }
        shoppingCartMapper.save(shoppingCart);

    }

    @Override
    public List<ShoppingCart> select(Long currentId) {
     return shoppingCartMapper.selectByUserId(currentId);
    }

    @Override
    public void cleam() {
        shoppingCartMapper.delete(BaseContext.getCurrentId());
    }
}
